from flask import Flask, request, jsonify, render_template, url_for
import pymysql
import datetime

app = Flask(__name__, template_folder='')

# 数据库连接配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'zhangjianfei',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

def get_db_connection():
    return pymysql.connect(**db_config)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit_diary():
    data = request.form
    date = data['date']
    weather = data['weather']
    mood = data['mood']
    event = data['event']

    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO diaries (date, weather, mood, event) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, event))
        connection.commit()
        return jsonify({'message': 'Diary submitted successfully!'}), 201
    except Exception as e:
        print(f"Error: {e}")  # 打印错误信息到控制台
        return jsonify({'error': str(e)}), 500
    finally:
        connection.close()

@app.route('/history')
def history():
    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM diaries ORDER BY created_at DESC")
            diaries = cursor.fetchall()
        return render_template('history.html', diaries=diaries)
    except Exception as e:
        print(f"Error: {e}")  # 打印错误信息到控制台
        return jsonify({'error': str(e)}), 500
    finally:
        connection.close()

if __name__ == '__main__':
    app.run( debug=True)
